package fons.model.ontology;

import java.util.Collection;
import java.util.Set;

import com.google.common.collect.Sets;

import fons.model.ontology.interfaces.Definable;
import fons.model.ontology.interfaces.Measurement;

@Definable
public final class SimpleMeasurement implements Measurement {

	private String unit;
	private String type;
	private final String qualifiedName;
	private final Context context;
		
	public SimpleMeasurement in (final String unit) {
		this.unit = unit;
		return this;
	}
	
	public SimpleMeasurement type (final String type) {
		this.type = type;
		return this;
	}
	
	@Override
	public String getType() {
		return type;
	}
	
	@Override
	public String getUnit() {
		return unit;
	}
	
	@Override
	public String getQualifiedName() {
		return this.qualifiedName;
	}
	
	SimpleMeasurement(final String qualifiedName, final Context context) {
		this.qualifiedName = qualifiedName;
		this.context = context;
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((context == null) ? 0 : context.hashCode());
		result = prime * result
				+ ((qualifiedName == null) ? 0 : qualifiedName.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		SimpleMeasurement other = (SimpleMeasurement) obj;
		if (context == null) {
			if (other.context != null)
				return false;
		} else if (!context.equals(other.context))
			return false;
		if (qualifiedName == null) {
			if (other.qualifiedName != null)
				return false;
		} else if (!qualifiedName.equals(other.qualifiedName))
			return false;
		return true;
	}

	@Override
	public String toString() {
		return "Measurement [unit=" + unit + ", type=" + type
				+ ", qualifiedName=" + qualifiedName + "]";
	}
	
	public static Measurement getComparableMeasurement (Collection<Value> values) {
		Set<SimpleMeasurement> measurements = Sets.newHashSet();
		for (Value value: values) {
			if (value != Context.missingValue)
				measurements.add(value.getMeasurement());
		}
		
		return measurements.size() == 1 ? measurements.iterator().next() : null;
	}
}
